package org.jeecg.modules.demo.storestaffreward.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basejobserve.entity.BaseJobServe;
import org.jeecg.modules.demo.basejobserve.service.IBaseJobServeService;
import org.jeecg.modules.demo.basestaffstatus.service.IBaseStaffStatusService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.projectgroup.entity.ProjectGroup;
import org.jeecg.modules.demo.projectgroup.service.IProjectGroupService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.storeproject.entity.StoreProject;
import org.jeecg.modules.demo.storeproject.service.IStoreProjectService;
import org.jeecg.modules.demo.storeprojectgroup.entity.StoreProjectGroup;
import org.jeecg.modules.demo.storeprojectgroup.service.IStoreProjectGroupService;
import org.jeecg.modules.demo.storestaffreward.entity.StoreStaffReward;
import org.jeecg.modules.demo.storestaffreward.service.IStoreStaffRewardService;
import org.jeecg.modules.util.BeanUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 分红管理
 * @Author: jeecg-boot
 * @Date: 2022-02-11
 * @Version: V1.0
 */
@Api(tags = "分红管理")
@RestController
@RequestMapping("/storestaffreward/storeStaffReward")
@Slf4j
public class StoreStaffRewardController extends JeecgController<StoreStaffReward, IStoreStaffRewardService> {
    @Autowired
    private IStoreStaffRewardService storeStaffRewardService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IProjectGroupService projectGroupService;
    @Autowired
    private IBaseJobServeService baseJobServeService;
    @Autowired
    private IStoreProjectService storeProjectService;
    @Autowired
    private IStoreProjectGroupService storeProjectGroupService;
    @Autowired
    private IBaseStaffStatusService baseStaffStatusService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     *
     * @param storeStaffReward
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "分红管理-分页列表查询")
    @ApiOperation(value = "分红管理-分页列表查询", notes = "分红管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StoreStaffReward storeStaffReward,
                                   @RequestParam(name = "type", defaultValue = "") String type,
                                   @RequestParam(name = "name", defaultValue = "") String name,
                                   @RequestParam(name = "groupId", defaultValue = "") String groupId,
                                   @RequestParam(name = "tradeActor", defaultValue = "") String tradeActor,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        insertRecordIfNeed(storeId);
        if (StringUtils.isBlank(type)) {
            return Result.error("请输入查询类型");
        }
        if (StringUtils.isBlank(tradeActor)) {
            return Result.error("请输入查询角色");
        }

        QueryWrapper<StoreStaffReward> queryWrapper = QueryGenerator.initQueryWrapper(storeStaffReward, req.getParameterMap());
        queryWrapper.eq("store_id", storeId);
        if (!StringUtils.isBlank(type)) {
            queryWrapper.eq("type", type);
        }
        if (!StringUtils.isBlank(groupId)) {
            queryWrapper.eq("relate_group_id", groupId);
        }
        if (!StringUtils.isBlank(tradeActor)) {
            queryWrapper.eq("trade_actor", tradeActor);
        }

        Page<StoreStaffReward> page = new Page<StoreStaffReward>(pageNo, pageSize);
        IPage<StoreStaffReward> pageList = storeStaffRewardService.page(page, queryWrapper);
        Map<String, Object> result = BeanUtils.bean2Map(pageList);
        List<Map<String, Object>> list = new ArrayList<>();

        for (StoreStaffReward r : pageList.getRecords()) {
            String vType = r.getType();
            Map<String, Object> map = BeanUtils.bean2Map(r);
            if ("1".equals(vType)) {
                CommodityManagement sell = commodityManagementService.getById(r.getRelateId());
                if (sell != null){
                    map.put("name", sell.getTradeName());
                    map.put("pic", sell.getProductPic());
                    map.put("price", sell.getProductPrice());
                    map.put("groupId", sell.getGroupId());
                    map.put("groupName", sell.getClassificationGoods());
                }


            } else if ("2".equals(vType)) {
                ProjectManagement sell = projectManagementService.getById(r.getRelateId());
                if (sell != null) {


                map.put("name", sell.getProjectName());
                map.put("pic", sell.getProjectPic());
                map.put("price", sell.getProjectPrice());
                map.put("groupId", sell.getGroupId());
                if (null != sell.getGroupId()) {
                    ProjectGroup byId = projectGroupService.getById(sell.getGroupId());
                    if (byId!= null){
                        map.put("groupName", byId.getGroupName());
                    }
                }

                }

            } else if ("3".equals(vType)) {
                BaseJobServe baseJobServe = baseJobServeService.getById(r.getRelateId());
                if (baseJobServe != null){
                    map.put("name", baseJobServe.getServeName());
                    map.put("relateId",baseJobServe.getId());
                    map.put("num", baseJobServe.getServeNum());
                }
            }
            if (!StringUtils.isBlank(name)) {
                if (r.getRelateName().contains(name)) {
                    list.add(map);
                }
            } else {
                list.add(map);
            }

        }

        result.put("records", list);

        return Result.OK(result);
    }

    private void insertRecordIfNeed(String storeId) {
        insertRecord4CommdityIfNeed(storeId);
        insertRecord4TimesCardIfNeed(storeId);
        insertRecord4ProjectIfNeed(storeId);

        List<Map> actorMaps = baseStaffStatusService.listTradeActor(storeId);


        List<String> actorList = new ArrayList<>();
        for (Map actorMap : actorMaps) {
            actorList.add(actorMap.get("id").toString());
        }


    }

    private void insertRecord4CommdityIfNeed(String storeId) {

        List<Map> actorMaps = baseStaffStatusService.listTradeActor(storeId);


        List<String> actorList = new ArrayList<>();
        for (Map actorMap : actorMaps) {
            actorList.add(actorMap.get("id").toString());
        }


        List<StoreStaffReward> list = new ArrayList<>();
        List<CommodityManagement> clist = commodityManagementService.list(new QueryWrapper<CommodityManagement>()
                .eq("store_id", storeId));


        for (CommodityManagement c : clist) {
            for (String actor : actorList) {
                List<StoreStaffReward> list1 = storeStaffRewardService.list(new QueryWrapper<StoreStaffReward>().eq("relate_id", c.getId()).eq("trade_actor", actor));
                if (list1.size() == 0) {

                    StoreStaffReward r = new StoreStaffReward();
                    r.setStoreId(storeId);
                    r.setType("1");
                    r.setTradeActor(actor);
                    r.setRelateId(c.getId());
                    r.setRelateName(c.getTradeName());
                    r.setRelateGroupId(c.getGroupId());

                    list.add(r);
                }
            }
        }

        storeStaffRewardService.saveBatch(list);
    }

    private void insertRecord4TimesCardIfNeed(String storeId) {
        List<Map> actorMaps = baseStaffStatusService.listTradeActor(storeId);


        List<String> actorList = new ArrayList<>();
        for (Map actorMap : actorMaps) {
            actorList.add(actorMap.get("id").toString());
        }



        List<ProjectManagement> clist = projectManagementService.list(new QueryWrapper<ProjectManagement>()
                .eq("store_id", storeId));

        List<StoreStaffReward> list = new ArrayList<>();
        for (ProjectManagement p : clist) {
            for (String actor : actorList) {
                List<StoreStaffReward> list1 = storeStaffRewardService.list(new QueryWrapper<StoreStaffReward>().eq("relate_id", p.getId()).eq("trade_actor", actor));
                if (list1.size() == 0) {
                    StoreStaffReward r = new StoreStaffReward();
                    r.setStoreId(storeId);
                    r.setType("2");
                    r.setTradeActor(actor);
                    r.setRelateId(p.getId());
                    r.setRelateName(p.getProjectName());
                    r.setRelateGroupId(p.getGroupId());
                    list.add(r);
                }
            }
        }
        storeStaffRewardService.saveBatch(list);
    }

    private void insertRecord4ProjectIfNeed(String storeId) {

        List<Map> actorMaps = baseStaffStatusService.listTradeActor(storeId);


        List<String> actorList1 = new ArrayList<>();
        for (Map actorMap : actorMaps) {
            actorList1.add(actorMap.get("id").toString());
        }

        List<StoreStaffReward> list = new ArrayList<>();
        //项目改为次卡管理的项目
        List<BaseJobServe> serves = baseJobServeService.list(new LambdaQueryWrapper<BaseJobServe>().eq(BaseJobServe::getStoreId, storeId));
        for (BaseJobServe p : serves) {
            for (String actor : actorList1) {
                List<StoreStaffReward> list1 = storeStaffRewardService.list(new QueryWrapper<StoreStaffReward>().eq("relate_id", p.getId()).eq("trade_actor", actor));
                if (list1.size() == 0) {
                    StoreStaffReward r = new StoreStaffReward();
                    r.setStoreId(storeId);
                    r.setType("3");
                    r.setTradeActor(actor);
                    r.setRelateId(p.getId());
                    r.setRelateName(p.getServeName());
                    list.add(r);
                }
            }
        }
        storeStaffRewardService.saveBatch(list);
    }

//
//
//    private void insertRecord4CommdityIfNeed(String storeId,  List<String> actorList1) {
//
//
//        List<String> ids = storeStaffRewardService.listNewCommodityId(storeId);
//
//        List<StoreStaffReward> list = new ArrayList<>();
//        List<CommodityManagement> clist = commodityManagementService.list(new QueryWrapper<CommodityManagement>()
//                .eq("store_id", storeId));
//        Map<String, CommodityManagement> map = new HashMap<>();
//        for (CommodityManagement c : clist) {
//            map.put(c.getId(), c);
//        }
//
//        for (String id : ids) {
//            for (String actor : actorList1) {
//                StoreStaffReward r = new StoreStaffReward();
//                r.setStoreId(storeId);
//                r.setType("1");
//                r.setTradeActor(actor);
//                r.setRelateId(id);
//                r.setRelateName(map.get(id).getTradeName());
//                r.setRelateGroupId(map.get(id).getGroupId());
//
//                list.add(r);
//            }
//        }
//
//        storeStaffRewardService.saveBatch(list);
//    }
//
//    private void insertRecord4TimesCardIfNeed(String storeId, List<String> actorList1) {
//
//
//        List<StoreStaffReward> list = new ArrayList<>();
//        List<String> ids = storeStaffRewardService.listNewTimeCardId(storeId);
//
//        List<ProjectManagement> clist = projectManagementService.list(new QueryWrapper<ProjectManagement>()
//                .eq("store_id", storeId));
//        Map<String, ProjectManagement> map = new HashMap<>();
//        for (ProjectManagement p : clist) {
//            map.put(p.getId(), p);
//        }
//
//        for (String id : ids) {
//            for (String actor : actorList1) {
//                StoreStaffReward r = new StoreStaffReward();
//                r.setStoreId(storeId);
//                r.setType("2");
//                r.setTradeActor(actor);
//                r.setRelateId(id);
//                r.setRelateName(map.get(id).getProjectName());
//                r.setRelateGroupId(map.get(id).getGroupId());
//
//                list.add(r);
//            }
//        }
//        storeStaffRewardService.saveBatch(list);
//    }
//
//    private void insertRecord4ProjectIfNeed(String storeId,List<String> actorList1) {
//
//
//        List<StoreStaffReward> list = new ArrayList<>();
//        List<String> ids = storeStaffRewardService.listNewCommodityId(storeId);
//        List<StoreProject> plist = storeProjectService.list(new QueryWrapper<StoreProject>()
//                .eq("store_id", storeId));
//        Map<String, StoreProject> map = new HashMap<>();
//        for (StoreProject p : plist) {
//            map.put(p.getId(), p);
//        }
//
//        for (String id : ids) {
//            for (String actor : actorList1) {
//                StoreStaffReward r = new StoreStaffReward();
//                r.setStoreId(storeId);
//                r.setType("3");
//                r.setTradeActor(actor);
//                r.setRelateId(id);
//                r.setRelateName(map.get(id).getName());
//                r.setRelateGroupId(map.get(id).getGroupId());
//
//                list.add(r);
//            }
//        }
//        storeStaffRewardService.saveBatch(list);
//    }

    /**
     * 添加
     *
     * @param storeStaffReward
     * @return
     */
    @AutoLog(value = "分红管理-添加")
    @ApiOperation(value = "分红管理-添加", notes = "分红管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StoreStaffReward storeStaffReward, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        storeStaffRewardService.save(storeStaffReward);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param storeStaffReward
     * @return
     */
    @AutoLog(value = "分红管理-编辑")
    @ApiOperation(value = "分红管理-编辑", notes = "分红管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StoreStaffReward storeStaffReward) {
        storeStaffRewardService.updateById(storeStaffReward);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "分红管理-通过id删除")
    @ApiOperation(value = "分红管理-通过id删除", notes = "分红管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        storeStaffRewardService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "分红管理-批量删除")
    @ApiOperation(value = "分红管理-批量删除", notes = "分红管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.storeStaffRewardService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "分红管理-通过id查询")
    @ApiOperation(value = "分红管理-通过id查询", notes = "分红管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StoreStaffReward storeStaffReward = storeStaffRewardService.getById(id);
        if (storeStaffReward == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(storeStaffReward);
    }

    @AutoLog(value = "分红管理-批量更新")
    @ApiOperation(value = "分红管理-批量更新", notes = "分红管理-批量更新")
    @PostMapping(value = "/saveBatch")
    public Result<?> updateBatch(@RequestBody List<StoreStaffReward> storeStaffRewards, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        // 项目提成不可设置比率
        Integer num = storeStaffRewards.stream().filter(i -> "3".equals(i.getType())&&"1".equals(i.getShareWay2())).collect(Collectors.toList()).size();
        if(num>0){
            return Result.error("项目不可设置按比率分成");
        }
        storeStaffRewardService.updateBatchById(storeStaffRewards);
        return Result.OK("添加成功！");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param storeStaffReward
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StoreStaffReward storeStaffReward) {
        return super.exportXls(request, storeStaffReward, StoreStaffReward.class, "分红管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StoreStaffReward.class);
    }

}
